package com.atguigu.daijia.driver.service.impl;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.Result;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.util.AuthContextHolder;
import com.atguigu.daijia.common.util.JwtUtil;
import com.atguigu.daijia.dispatch.client.NewOrderFeignClient;
import com.atguigu.daijia.driver.client.DriverInfoFeignClient;
import com.atguigu.daijia.driver.service.DriverService;
import com.atguigu.daijia.map.client.MapFeignClient;
import com.atguigu.daijia.model.form.driver.DriverFaceModelForm;
import com.atguigu.daijia.model.form.driver.UpdateDriverAuthInfoForm;
import com.atguigu.daijia.model.vo.driver.DriverAuthInfoVo;
import com.atguigu.daijia.model.vo.driver.DriverLoginVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class DriverServiceImpl implements DriverService {

    @Resource
    private DriverInfoFeignClient client;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MapFeignClient mapFeignClient;

    @Resource
    private NewOrderFeignClient newOrderFeignClient;

    @Override
    public String login(String code) {

        // 1. 判断code是否是null
        if (!StringUtils.hasText(code)) {
            throw new GuiguException(ResultCodeEnum.LOGIN_MOBLE_ERROR);
        }
        // 2. 根据code获取司机id--远程调用
        Result<Long> result = client.login(code);
        // result 是否正常返回
        if (result.getCode() != 200) {
            throw new GuiguException(ResultCodeEnum.LOGIN_MOBLE_ERROR);
        }
        Long driverId = result.getData();
        //  判断driverId是否正确
        if (driverId == null) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        // 3. 根据driverId生成jwt
        String jwt = JwtUtil.generateJWT(driverId.toString());

        // 4. 将jwt存入redis
        stringRedisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + jwt,
                driverId.toString(),
                RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
        // 5. 返回jwt
        return jwt;
    }

    @Override
    public DriverLoginVo getDriverInfo(String token) {
        // 1. 获取driverId
        Long driverId = AuthContextHolder.getUserId();
        // 2. 远程调用获取 DriverLoginVo
        Result<DriverLoginVo> result = client.getDriverInfo(driverId);
        if (result.getCode() != 200) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        DriverLoginVo data = result.getData();
        if (ObjectUtils.isEmpty(data)) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        return data;
    }

    @Override
    public Boolean updateDriverAuthInfo(UpdateDriverAuthInfoForm updateDriverAuthInfoForm) {
        if(ObjectUtils.isEmpty(updateDriverAuthInfoForm)){
            throw new GuiguException(ResultCodeEnum.ARGUMENT_VALID_ERROR);
        }
        updateDriverAuthInfoForm.setDriverId(AuthContextHolder.getUserId());
        Result<Boolean> result = client.updateDriverAuthInfo(updateDriverAuthInfoForm);
        if (result.getCode()!=200) {
            throw new GuiguException(ResultCodeEnum.ARGUMENT_VALID_ERROR);
        }

        return result.getData();
    }

    @Override
    public Boolean creatDriverFaceModel(DriverFaceModelForm driverFaceModelForm) {
        driverFaceModelForm.setDriverId(AuthContextHolder.getUserId());
        Result<Boolean> booleanResult = client.creatDriverFaceModel(driverFaceModelForm);
        return booleanResult.getData();
    }

    @Override
    public DriverAuthInfoVo getDriverAuthInfo() {
        Long driverId = AuthContextHolder.getUserId();
        Result<DriverAuthInfoVo> result = client.getDriverAuthInfo(driverId);
        if (result.getCode() !=200) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        return result.getData();
    }

    @Override
    public Boolean isFaceRecognition() {
        Long driverId = AuthContextHolder.getUserId();
        Result<Boolean> result = client.isFaceRecognition(driverId);
        if (result.getCode()!=200) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        return result.getData();
    }

    @Override
    public Boolean verifyDriverFace(DriverFaceModelForm driverFaceModelForm) {
        Result<Boolean> result = client.verifyDriverFace(driverFaceModelForm);
        if (result.getCode()!=200) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        return result.getData();
    }

    @Override
    public Boolean startService(Long driverId) {
        // 1. 先判断司机有没有认证
        DriverLoginVo driverLoginVo = client.getDriverInfo(driverId).getData();
        if(driverLoginVo.getAuthStatus()!=2) {
            throw new GuiguException(ResultCodeEnum.AUTH_ERROR);
        }
        // 2. 判断是否进行人脸检测
        Result<Boolean> faceRecognitionResult = client.isFaceRecognition(driverId);
        if (!faceRecognitionResult.getData()){
            throw new GuiguException(ResultCodeEnum.FACE_ERROR);
        }
        // 3. 删除redis中司机当前的位置信息
        mapFeignClient.removeDriverLocation(driverId);
        // 4. 删除redis中司机的任务队列
        newOrderFeignClient.clearNewOrderQueueData(driverId);

        // 5. 更改司机的接单状态
        client.updateServiceStatus(driverId,1);
        return true;
    }

    //停止接单服务
    @Override
    public Boolean stopService(Long driverId) {
        //更新司机的接单状态 0
        client.updateServiceStatus(driverId,0);

        //删除司机位置信息
        mapFeignClient.removeDriverLocation(driverId);

        //清空司机临时队列
        newOrderFeignClient.clearNewOrderQueueData(driverId);
        return true;
    }
}
